/*
 * Copyright 2007-2010 GP Software
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * UnicodeConverter.java | Created on November 2, 2007
 */
package com.pacm.i18n;


/**
 * Converts Unicode characters to its ASCII equivalent
 *
 * @author Paul Augustine C. Mendoza
 * @since 1.0
 */
public class UnicodeConverter {

    /** Restricted constructor */
    private UnicodeConverter() {
        // Do nothing...
    }

    /**
     * Converts a Unicode character string to its ASCII equivalent
     *
     * @param data the data to convert
     * @return ASCII string equivalent
     */
    public static String toAscii(String data) {
        StringBuffer sb = new StringBuffer();
        UnicodeConverter converter = new UnicodeConverter();
        char[] chars = data.toCharArray();
        for (char character : chars) {
            String c;
            int testBit = (int) character;
            if ((testBit < Byte.MIN_VALUE) || (testBit > Byte.MAX_VALUE)) {
                c = converter.getAscii(character);
            } else {
                c = Character.toString(character);
            }
            sb.append(c);
        }
        return sb.toString();
    }

    /**
     * Converts a Unicode character to its ASCII equivalent
     *
     * @param character the character to convert
     * @return ASCII character equivalent
     */
    private String getAscii(int character) {
        String testStr = Integer.toHexString(character);
        StringBuffer sb = new StringBuffer();
        int len = 4 - testStr.length();
        // Add spacers
        for (int i = 0; i < len; i++) {
            sb.append("0");
        }
        sb.append(testStr);
        return "\\u" + sb.toString();
    }

}
